import serial, threading, time

record = []
tmps = ""
tmpa = {}
def record_func(secs=120):
    global record, tmps, tmpa
    duration = 0
    ts = 1e-6
    tik = 0
    with serial.Serial('COM5', 460800) as ser:
        while True:
            inp = ser.read()
            if inp == b"\n" or inp == b'\r':
                if not ":" in tmps:
                    tmps = ""
                    continue
                res = tmps.split(':')
                name = res[0]
                if len(res)==1:
                    continue
                value = res[1]
                if name == "UVW":
                    ua,ub,uc = value.split('|')
                    tmpa["Ua"] = float(ua)
                    tmpa["Ub"] = float(ub)
                    tmpa["Uc"] = float(uc)
                    ts = tmpa.get('interval', 1e-6)
                    record.append(tmpa)
                    tmpa = {}
                    tmpa["tik"] = tik
                    tik = 1e-6
                elif name == "PWM":
                    da,db,dc = value.split('|')
                    tmpa["Da"] = float(da)
                    tmpa["Db"] = float(db)
                    tmpa["Dc"] = float(dc)
                else:
                    try:
                        tmpa[name] = float(value)
                    except:
                        tmpa[name] = value
                tmps = ""
            else:
                tik += ts
                try:
                    tmps += inp.decode()
                except:
                    continue
            duration += ts
            print(duration)
            if duration > secs:
                break
# working = threading.Thread(target=record_func)
# working.start()
record_func()
            
# ser.close()
            
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np

pwm = [[x.get('Da', 1e-6), x.get('Db', 1e-6), x.get('Dc', 1e-6)] for x in record]
x = [x.get('tik', 1e-6) for x in record]
cx = np.cumsum(x)
plt.figure()
plt.plot(cx, pwm)
plt.show()

plt.figure()
plt.plot(cx)
plt.show()